import paramiko
from scp import SCPClient


def download_file_from_server(hostname, port, username, password, remote_file_path, local_file_path):
    try:
        # 创建 SSH 客户端
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接到远程服务器
        ssh.connect(hostname, port=port, username=username, password=password)

        # 使用 SCP 从服务器下载文件
        with SCPClient(ssh.get_transport()) as scp:
            scp.get(remote_file_path, local_file_path)

        print(f"文件成功下载到 {local_file_path}")

    except Exception as e:
        print(f"下载文件时发生错误: {e}")

    finally:
        ssh.close()


if __name__ == "__main__":
    hostname = '192.168.31.65'  # 远程服务器的 IP 地址或主机名
    port = 22  # SSH 默认端口是 22
    username = 'hdxt'  # 你的服务器用户名
    password = '111111'  # 你的服务器密码
    remote_file_path = '/usr/local/src/second-generation-underground/sensor_data.db'  # 服务器上的文件路径
    local_file_path = '/Users/tancongyuan/Desktop/sensor_data.db'  # 本地保存的文件路径

    download_file_from_server(hostname, port, username, password, remote_file_path, local_file_path)